package com.glory.dgcpcpda.activity.mfg;

import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.recipe.ProgramDownLoadActivity;
import com.glory.dgcpcpda.adapter.LotBatchListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.UpdateIPEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import java.util.Arrays;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class WorkBatchBeginActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;

    private LotBatchListAdapter mAdapter;
    private int mCount = 0;
    private String type;
    private  List<AdrefListEntity.Adref> adreflist = new ArrayList<>() ;
    private  ArrayList<String> StepNameList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_batch_begin;
    }

    @Override
    protected void initView() {
        StepNameList.clear();
        setMainLayout(llMain);
        tvTitle.setText("批量进站");
        tvBaseSubmit.setVisibility(View.GONE);
        initRecyclerView(rvLotList, this);
        tvCount.setText("计数:" + mCount);
        mAdapter = new LotBatchListAdapter(null, false, () -> tvCount.setText("计数:" + --mCount));
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvLotList.setAdapter(mAdapter);
        type="DefaultTrackOut";
        showCarrierLayout();

        initEdit(etEqpWorkID, s -> etLot.requestFocus());

        initEdit(etLot, s -> {
            etLot.setText("");
            new Handler().postDelayed(() -> etLot.requestFocus(), 500);
            if (containLot(s, mAdapter.getData())) {
                showToast("当前批次已在列表中", false);
                return;
            }

            LotUtils.searchLotInfo(WorkBatchBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {

                    if ("".equals(getText(etUserName))){
                        showToast("请先输入工号", false);
                        return;
                    }

                    if (!response.getLOT().getSTATE().equals("等待作业")) {
                        showToast("批次状态不允许", false);
                        return;
                    }
                    //增加批量工步
                    if(!StepNameList.contains(response.getLOT().getSTEPNAME())){
                        showToast("工序不允许", false);
                        return;
                    }
//                    if (!response.getLOT().getSTEPNAME().equals("A2020")
//                            &&!response.getLOT().getSTEPNAME().equals("A2110")
//                            &&!response.getLOT().getSTEPNAME().equals("A2210")
//                            &&!response.getLOT().getSTEPNAME().equals("A4200")
//                            &&!response.getLOT().getSTEPNAME().equals("A3200")
//                            &&!response.getLOT().getSTEPNAME().equals("A9021")
//                            &&!response.getLOT().getSTEPNAME().equals("A7200")
//                            &&!response.getLOT().getSTEPNAME().equals("A9011")
//                            &&!response.getLOT().getSTEPNAME().equals("A9013")
//                            &&!response.getLOT().getSTEPNAME().equals("A9024")
//                            &&!response.getLOT().getSTEPNAME().equals("A9026")
//                            &&!response.getLOT().getSTEPNAME().equals("A1900")
//                            &&!response.getLOT().getSTEPNAME().equals("A3300")
//                            &&!response.getLOT().getSTEPNAME().equals("A6100")
//                            &&!response.getLOT().getSTEPNAME().equals("A7210")
//                            &&!response.getLOT().getSTEPNAME().equals("T1025")
//                            &&!response.getLOT().getSTEPNAME().equals("A2500")
//                            &&!response.getLOT().getSTEPNAME().equals("A5010")
//                            &&!response.getLOT().getSTEPNAME().equals("A6200")) {
//                        showToast("工序不允许", false);
//                        return;
//                    }

                    if(response.getLOT().getSTEPNAME().equals("A3200")){
                        if(response.getLOT().getCUSTOMERCODE().equals("JK1841")||response.getLOT().getCUSTOMERCODE().equals("GD1841")){
                            showConfirmDialog("客户代码"+response.getLOT().getCUSTOMERCODE()+"键合批检QC不需要抽检");
                            return;
                        }
                    }

                    if(response.getLOT().getSTEPNAME().equals("A3200")||response.getLOT().getSTEPNAME().equals("A9021")||response.getLOT().getSTEPNAME().equals("A6100")){
                        type="NoEqpTrackIn";
                        etEqpWorkID.setText("");
                    }else if (!response.getLOT().getSTEPNAME().equals("A3200")&&!response.getLOT().getSTEPNAME().equals("A9021")&&!response.getLOT().getSTEPNAME().equals("A6100")){
                        if (getText(etEqpWorkID).equals("")) {
                            showToast("请先扫描设备ID", false);
                            return;
                        }
                        type="DefaultTrackIn";
                    }


                    if (response.getLOT().getHOLDSTATE().equals("On")) {
                        showToast("批次状态不允许", false);
                        return;
                    }

                    if (mAdapter.getData().size() <= 0) {
                        submit(s);
                    } else {
                        submit(s);
                        /*if (mAdapter.getData().get(0).getSTEPNAME().equals(response.getLOT().getSTEPNAME())) {
                            submit(s);
                        }else {
                            showToast("扫描批次工序与列表批次工序不一致，无法添加.", false);
                        }*/
                    }

                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

    }

    private boolean containLot(String s, List<LotInfoEntity.LotBean> data) {
        if (data.size() <= 0)
            return false;
        for (LotInfoEntity.LotBean entity : data) {
            if (entity.getLOTID().equals(s))
                return true;
        }
        return false;
    }

    //获取MES动态栏位参考值
    private void showCarrierLayout() {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    adreflist = response.body().getResponse().getBody().getADREFLIST();
                    for(int i=0;i<adreflist.size();i++)
                    {
                        StepNameList.add((adreflist.get(i).getKEY()));
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","PDA_Batch_Check_In");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
//        if (mAdapter.getData().size() <= 0) {
//            showToast("请先添加批次信息",false);
//            return;
//        }
//
//        if (getText(etEqpWorkID).equals("")){
//            showToast("请先扫描设备ID",false);
//            return;
//        }

        if (getText(etUserName).equals("")){
            showToast("请输入工号",false);
            return;
        }

        //批量进站
        FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
            @Override
            public void onSuccess() {
                //确定
                FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                        (new TypeToken<BaseResponseBean<JSONObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showToast("进站成功", true);
                            mAdapter.getData().clear();
                            etEqpWorkID.setText("");
                            etLot.setText("");
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<JSONObject>> response) {
                        super.onError(response);
                        loadError(response.getException(), "LOTTRACKIN");
                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", type);
                map.addProperty("EQUIPMENTID", getText(etEqpWorkID));
                map.addProperty("ISCHECKSTEPAUTHORITY", true);
//                List<LotList> lotList = new ArrayList<>();
//                for (LotInfoEntity entity : mAdapter.getData()) {
//                    lotList.add(new LotList(entity.getLOT().getLOTID()));
//                }
//                map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
                NetUtils.mRequestPostNet("CPC.LOTTRACKIN", getText(etUserName),"LOTTRACKIN", this, map, callBack);

            }
        }, () -> {
        }).show(getSupportFragmentManager(), "SUBMIT_DIALOG");
    }

    private void submit(String lotID) {
        //确定
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showToast("进站成功", true);
                    mAdapter.addData(response.body().getResponse().getBody().getLOTLIST());
                    tvCount.setText("计数:" + mAdapter.getData().size());
                }
                etLot.setText("");
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTTRACKIN");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", type);
        map.addProperty("EQUIPMENTID", getText(etEqpWorkID));
        map.addProperty("ISCHECKSTEPAUTHORITY", true);
        List<LotList> lotList = new ArrayList<>();
        lotList.add(new LotList(lotID));
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
        NetUtils.mRequestPostNet("CPC.LOTTRACKIN", getText(etUserName),"LOTTRACKIN", this, map, callBack);
//        NetUtils.requestMESPostNet("CPC.LOTTRACKIN",  this, map, callBack);
    }
}